<!--选择页（人员、站点、设备）-->
<template>
	<view class="select-main">
		<nav-bar class="header" back :title="title" @goBack="goBack" />
		<view class="main-container">
			<!-- 搜索框  -->
			<view class="search">
				<van-search disabled left-icon="" right-icon="search" placeholder="请输入人员" @click="showSearch = true;" />
			</view>

			<!-- 面包屑 -->
			<view class="breadcrumb">
				<view class="breadcrumb-item" v-for="(item, index) in breadcrumbList" :key="item.id"
					@click="handSelAction(item,index)">
					{{item.NAME}}
				</view>
			</view>

			<van-tabs type="card" class="select_content_tabs" animated>
				<van-tab v-for="(item) in breadcrumbList" :key="item.id" :title="item.NAME" :name="item.NAME">
					<!-- {{item.NAME}} -->
					<view class="option-list-with-sub">
						<van-cell clickable @click="checkAll"
							v-if="currentOperatorList && currentOperatorList.length>0">
							<template #title>
								<!-- <van-radio name="1"> 全选</van-radio> disabled -->
								<van-checkbox v-model="allSelect" class="all" ref="allCheckbox">全选</van-checkbox>
							</template>
						</van-cell>
					</view>

					<!-- 选项列表-含子选项 -->
					<view class="option-list-with-sub-child">
						<van-cell-group>
							<van-cell v-for="item in currentOrgList" clickable :key="item.ORGID" :title="item.NAME"
								@click.stop="toSub(item)">
								<template #title>
									{{ item.NAME }}
									<!-- 全选需要进一步实现 -->
									<!-- <van-checkbox  v-model="item.isChecked" :name="JSON.stringify(item)" ref="subCheckboxes">{{item.NAME}}</van-checkbox> -->
								</template>
								<template #right-icon>
									<view class="sub">
										<img src="../../../static/img/sub.png" alt="">
									</view>
								</template>
							</van-cell>
						</van-cell-group>
					</view>

					<!-- 选项列表-不含子选项-->
					<view class="option-list-child">
						<van-cell-group>
							<van-cell v-for="item in currentOperatorList" :key="item.ORGID" :title="item.NAME">
								<template #title>
									<van-checkbox @change="selectOperator($event, item)" v-model="item.isChecked"
										:name="JSON.stringify(item)">{{item.NAME}}</van-checkbox>
								</template>
							</van-cell>
						</van-cell-group>
					</view>
				</van-tab>
			</van-tabs>

		</view>
		<view class="bottom-container">
			<view class="select-result" @click="resultShow= true">
				<view class="sel_res_lf">
					<view v-if="resMapLength > 0">
						已选择：{{resMapLength+'个'}}
						<van-icon name="arrow-up" />
					</view>
					<view class="sel_res_text" v-if="resMapLength > 0">{{resMapText}}</view>
				</view>
			</view>
			<text v-if="resMapLength > 0" class="clr-btn" @click="clear()">清空</text>
			<van-button color="#417ADC" @click="subComfirm">确定</van-button>
		</view>
		<van-action-sheet v-model="resultShow">
			<van-cell :title="`已选择${ resMapLength }人`">
				<template #right-icon>
					<van-button round type="info" size="mini" style="width:px2vw(40)" class="p08"
						@click="resultShow=false">确 认</van-button>
				</template>
			</van-cell>
			<van-list class="list-wrap">
				<van-cell :title="item.NAME" v-for="item in resMap" :key="item.NAME">
					<template #right-icon>
						<van-button @click="deleteChange(item)" type="danger" size="mini" class="p08" round>移 除
						</van-button>
					</template>
				</van-cell>
			</van-list>
		</van-action-sheet>
		<!--弹出搜索页-->
		<van-popup v-model="showSearch" position="right">
			<div class="search-main">
				<!-- <nav-bar class="header" back title="搜索" @goBack="doCancel" /> -->
				<div class="main-container">
					<div class="search-container">
						<form action="/">
							<van-search v-model="searchValue" show-action placeholder="请输入搜索关键词" @input="doSearch"
								@clear="doClear" @cancel="doCancel" />
						</form>
						<div class="search-content">
							<van-loading size="24px" v-if="isLoading" vertical>加载中...</van-loading>

							<template v-else>
								<div class="list-ul">
									<div class="list-item" v-for="(e, i) in resultList" :key="i"
										@click="handleClick(e)">
										<span class="item-left">{{ e.name.length>2?e.name.slice(-2): e.name }}</span>
										<div class="item-right">
											<span class="item-name">{{ e.name }}</span>
											<span class="item-dept">{{e.dept}}</span>
										</div>
									</div>
									<div class="list-off" v-if="searchValue&&resultList.length==0">
										未搜到关于"{{this.searchValue}}"</div>
								</div>
							</template>

						</div>
					</div>
				</div>
			</div>
		</van-popup>
	</view>
</template>

<script>
	import {
		mapGetters
	} from 'vuex'
	import {
		debounce
	} from '../../../utils/index.js'
	import navBar from '../../../components/common/nav-bar.vue'
	import search from './search'
	export default {
		name: 'selectUser',
		components: {
			navBar,
			search
		},
		computed: {
			...mapGetters(['selectUser', "userData"])
		},
		data() {
			return {
				selActive: '省公司', // 当前选中的title
				resultShow: false,
				title: '选择人员',
				showSearch: false,
				searchValue: '',
				breadcrumbList: [], // 标题面包屑

				rawList: {},
				currentOrgList: [], // 当前组织列表
				currentOperatorList: [], // 当前人员列表
				allSelect: false,
				resMap: {},
				resMapLength: 0, // 响应性存在问题，需要记录长度
				resMapText: '',

				isClear: false,
				resultList: [],
				isLoading: false
			}
		},
		onLoad(option) {},
		props: {
			selected: {
				type: Object,
				define: function() {
					return {
						ids: [],
						text: ''
					}
				}
			},
			//是单选radio还是多选checkbox
			selectStatus: {
				type: String,
				default: "checkbox"
			}
		},
		watch: {
			selected: {
				handler: function(newVal) {
					this.$nextTick(() => {
						if (newVal && newVal.ids) {
							// this.resList = newVal.ids
							if (newVal.ids) {
								this.resMapLength = newVal.ids.length
								this.resMapText = newVal.text
							}
							// this.resMap = {}
							// this.setCurCheckItem(this.rawList[0])
						} else {
							this.resMapLength = 0
							this.resMapText = ''
							// this.resMap = {}
						}
						this.getOrgList()
					})
				},
				immediate: true,
				deep: true
			},
			resMap: {
				handler: function(newVal) {
					this.resMapLength = Object.values(newVal).length
				},
				immediate: true,
				deep: true
			}
		},
		mounted() {

		},
		methods: {
			// 搜索结果页
			handleClick(e) {
				if (this.selectStatus === "radio") {
					//看是否搜索选中后，添加在列表显示
					// this.currentOperatorList.map(item => {
					// 	item.isChecked = false
					// })
					// this.currentOperatorList.push({
					// 	NAME: e.name,
					// 	ORGID: e.id,
					// 	isChecked: true
					// })
					// let peoples = this.currentOperatorList.filter(item => {
					// 	if (item.isChecked) {
					// 		return item
					// 	}
					// })
					// this.resMapLength = peoples.length
					// peoples.forEach(name => {
					// 	this.resMapText = name.NAME
					// })
					this.selected.ids = []
					this.selected.ids.push(e.id)
					this.selected.text = e.name
				} else {
					// 添加到勾选结果页
					this.selectOperator(true, {
						ORGID: e.id,
						NAME: e.name
					})

					if (this.selected.ids instanceof Array && this.selected.ids.indexOf(e.id) == -1) {
						// 勾选动作
						this.selected.ids.push(e.id)
						this.selected.text += `,${e.name}`
						this.setCurCheckItem(this.rawList)
					}
				}
				this.showSearch = false
			},
			goBack() {
				// uni.navigateBack()
				this.$emit('cancel')
			},
			clear() {
				this.resMapLength = 0
				this.resMapText = ''
				this.resMap = {}
				this.isClear = true
				this.rawList = this.formatterList(this.rawList)
				this.currentOrgList = this.rawList[0].lwOrgList
				this.currentOperatorList = this.rawList[0].operatorList
				this.breadcrumbList = [this.rawList[0]]
				this.selActive = this.rawList[0].NAME
				this.isClear = false
			},
			doCancel() {
				this.resultList = []
				this.showSearch = false
			},
			doClear() {
				this.searchValue = ''
			},
			doSearch() {
				this.isLoading = true
				this.handleDebGet()
			},
			handleDebGet: debounce(function() {
				// 模糊匹配-防抖
				this.$apiRequest.bzhzyApi
					.selectUserListByName({
						name: this.searchValue,
						orgId: this.userData.deptId,
						roleId: this.userData.deptId,
					})
					.then(res => {
						this.resultList = res.data
						this.isLoading = false
					})
			}, 1200),
			selectOperator(isChecked, operator) {
				if (isChecked) {
					// 选中状态
					this.resMap[operator.ORGID] = operator
					this.$set(this.resMap, operator.ORGID, operator)
					if (this.selectStatus === "radio") {
						this.currentOperatorList.forEach(item => {
							if (item.ORGID !== operator.ORGID) {
								item.isChecked = false
							} else {
								item.isChecked = true
							}
						})
					}

				} else {
					// 切换为未选中状态
					this.deleteChange(operator)
				}
				//单选业务
				if (this.selectStatus === "radio") {
					let peoples = this.currentOperatorList.filter(item => {
						if (item.isChecked) {
							return item
						}
					})
					peoples.forEach(name => {
						this.resMapText = name.NAME
					})
					this.resMapLength = peoples.length
				} else { //多选业务

					this.resMapLength = Object.values(this.resMap).length
					const names = Object.values(this.resMap).map(item => {
						return item.NAME
					})
					if (names.length > 3) {
						const firstPeple = names.slice(0, 3).toString()
						this.resMapText = firstPeple + `等${names.length}人`
					} else {
						this.resMapText = names.toString()
					}
				}
				this.handAllSelectStatus()
			},
			checkAll() {
				// alert('暂未实现')
				this.allSelect = !this.allSelect
				this.currentOperatorList.map(item => {
					item.isChecked = this.allSelect
				})
			},
			clearItem(userList) {
				//  this.rawList[0].operatorList
				this.rawList = this.formatterList(this.rawList)
				this.currentOrgList = this.rawList[0].lwOrgList
				this.currentOperatorList = this.rawList[0].operatorList
				this.breadcrumbList = [this.rawList[0]]
				this.selActive = this.rawList[0].NAME
			},
			setCurCheckItem(userList) {
				userList.forEach(item => {
					if (this.selected.ids.indexOf(item.ORGID) != -1) {
						item.isChecked = true
					} else {
						item.isChecked = false
					}
					if (item.lwOrgList) {
						this.setCurCheckItem(item.lwOrgList)
					}
					if (item.operatorList) {
						this.setCurCheckItem(item.operatorList)
					}
				})
			},
			subComfirm() {
				let users = []
				let resArr = []
				//单选处理
				if (this.selectStatus === "radio") {
					this.currentOperatorList.forEach(item => {
						if (item.isChecked) {
							users.push(item.ORGID)
						}
					})
					console.log(this.selected, users)
					this.$emit('update:selected', {
						ids: users.length > 0 ? users : this.selected.ids,
						text: this.resMapText
					})
					this.$emit('comfirm')
				} else { //多选处理
					resArr = [...Object.values(this.resMap)]
					users = resArr.map(item => {
						return item.ORGID
					})
					this.$emit('update:selected', {
						ids: resArr.length > 0 ? users : [],
						text: this.resMapText
					})
					this.$emit('comfirm')
				}

			},
			getOrgList() {
				this.$apiRequest.bzhzyApi
					.selectLwOrgList({
						userName: ""
					})
					.then(res => {
						if (res.data) {
							this.resMap = {}
							this.rawList = this.formatterList(res.data.lwOrgList)
							this.currentOrgList = this.rawList[0].lwOrgList ? this.rawList[0].lwOrgList :
							[] // 首次加载为第一层
							this.currentOperatorList = this.rawList[0].operatorList ? this.rawList[0].operatorList :
							[] // 首次加载为第一层
							this.breadcrumbList = [this.rawList[0]]
							this.selActive = this.rawList[0].NAME
							// 面包屑默认顶级
							this.handSelAction(this.breadcrumbList[0], 0)
						}
					})
			},
			formatterList(list) {
				return (
					list &&
					list.map(item => {
						item.isChecked = false
						// 是否正在清空操作
						if (!this.isClear) {
							if (
								this.selected.ids &&
								this.selected.ids.indexOf(item.ORGID) != -1
							) {
								item.isChecked = true
								this.resMap[item.ORGID] = {
									NAME: item.NAME,
									ORGID: item.ORGID,
									PARENTID: item.PARENTID,
									isChecked: true
								}
								this.$set(this.resMap, item.ORGID, {
									NAME: item.NAME,
									ORGID: item.ORGID,
									PARENTID: item.PARENTID,
									isChecked: true
								})
							} else {
								item.isChecked = false
							}
						}

						if (item.lwOrgList) {
							this.formatterList(item.lwOrgList)
						}

						if (item.operatorList) {
							this.formatterList(item.operatorList)
						}

						return item
					})
				)
			},
			toSub(item) {
				this.breadcrumbList.push(JSON.parse(JSON.stringify(item)))
				// 切换当前组织列表
				this.currentOrgList = item.lwOrgList
				// this.currentOperatorList = item.operatorList
				this.currentOperatorList = item.operatorList.map(item => {
					if (this.resMap && this.resMap[item.ORGID]) {
						item.isChecked = true
					} else {
						item.isChecked = false
					}
					return item
				})
				this.handAllSelectStatus()
				this.selActive = item.NAME
			},
			handAllSelectStatus() {
				// 当前展开全选按钮状态管理
				let idx = 0
				let len = null
				if (this.currentOperatorList) {
					len = this.currentOperatorList.length
					this.currentOperatorList.filter(item => {
						if (item.isChecked) {
							idx++
						}
					})
				}

				if (idx == len) {
					this.allSelect = true
				} else {
					this.allSelect = false
				}
			},
			handSelAction(item, i) {
				this.selActive = item.NAME
				this.currentOrgList = item.lwOrgList
				this.currentOperatorList = item.operatorList
				this.breadcrumbList = JSON.parse(
					JSON.stringify(this.breadcrumbList.slice(0, i + 1))
				)
			},
			deleteChange(operator) {
				// 同步列表
				this.currentOperatorList = this.currentOperatorList.map(item => {
					if (item.ORGID === operator.ORGID) {
						item.isChecked = false
					}
					return item
				})

				// 同步父组件
				// delete this.resMap[operator.ORGID]
				// operator.isChecked = false
				this.resMap = Object.values(this.resMap).reduce((prev, item) => {
					if (item.ORGID !== operator.ORGID) {
						prev[item.ORGID] = item
						return prev
					}

					return prev
				}, {})
			}
		}
	}
</script>

<style scoped lang="scss">
	.select-main {
		height: 100vh;
		background-color: #f8f8f8;
		font-family: vant-icon;

		.header {
			position: sticky;
			top: 0;
			z-index: 9;
		}

		.main-container {
			min-height: calc(100vh - #{px2vh(363)});
			padding: px2vh(30) px2vw(30) px2vh(30) px2vw(30);

			.search {
				width: px2vw(1020);
				height: px2vh(110);
				margin: auto auto px2vh(50);
				border-radius: $border-radius-base;
				overflow: hidden;

				.van-search {
					padding: 0;
					height: px2vh(110);

					.van-search__content {
						background: #fff;
						height: 38px;
					}
				}

				/deep/.van-field__control {
					height: 30px;
				}
			}

			.breadcrumb {
				display: flex;
				justify-content: flex-start;
				padding-bottom: px2vh(28);
				overflow: auto;

				.breadcrumb-item {
					display: flex;
					align-items: center;
					margin-right: px2vw(10);
					font-size: px2vh(42);
					color: #666666;
					flex-shrink: 0;
				}

				.breadcrumb-item:not(:first-child)::before {
					margin-right: px2vw(10);
					content: '\F00A';
					color: #666666;
				}

				.breadcrumb-item:last-child {
					color: #417adc;
				}
			}

			.option-list-with-sub,
			.option-list {
				border-radius: $border-radius-base;
				overflow: hidden;
				background-color: #ffffff;
			}

			.option-list-with-sub-child {
				// margin-bottom: px2vh(30);

				.sub {
					//width: px2vw(82);
					//height: 100%;
					text-align: center;

					img {
						width: px2vw(41);
					}
				}
			}
		}

		.bottom-container {
			display: flex;
			justify-content: space-between;
			align-items: center;
			position: sticky;
			bottom: 0;
			height: px2vh(100);
			padding: px2vh(20) px2vw(40) px2vh(20) px2vw(49);
			background-color: #fff;

			.select-result {
				width: calc(100% - #{px2vw(240)} - #{px2vw(67)});
				// background: #acf;
				display: flex;
				align-items: center;
				justify-content: flex-start;

				.sel_res_lf {
					display: flex;
					flex-direction: column;
					align-items: flex-start;
					justify-content: center;
					color: #417adc;
				}

				.sel_res_text {
					max-width: px2vw(530);
					overflow: hidden;
					text-overflow: ellipsis;
					white-space: nowrap;
				}
			}

			.clr-btn {
				color: #ee0a24;
				width: px2vw(120);
			}

			.van-button {
				height: px2vh(100);
				width: px2vw(240);
				font-size: px2vh(42);
				border-radius: px2vh(20);
			}
		}

		.option-list-with-sub {
			width: px2vw(1020);
			max-height: px2vh(1360);
			overflow-y: auto;
		}
	}

	.list-wrap {
		height: px2vh(600);
		margin-bottom: px2vh(20);
		overflow-y: auto;
	}

	.p08 {
		padding: 0 px2vw(20);
	}

	// 搜索结果页
	.search-main {
		height: 100vh;
		width: 100vw;

		.search-container {
			.van-search__action {
				padding: 0 12px;
				color: #417adc;
			}

			width: 100%;
		}

		.search-content {
			.list-ul {
				.list-off {

					display: flex;
					align-items: center;
					justify-content: center;
				}
			}

			.list-item {
				display: flex;
				align-items: center;
				justify-content: flex-start;
				margin: px2vh(20) 0;
				background-color: #f8f8f8;
				padding: px2vh(10) px2vw(40);
				border-radius: px2vh(10);

				.item-left {
					display: flex;
					align-items: center;
					justify-content: center;
					width: px2vw(150);
					height: px2vw(150);
					vertical-align: middle;
					background-color: #6693e0;
					border-radius: px2vh(10);
					margin-right: px2vw(20);
					padding: 0 px2vw(10);
					color: #fff;
					font-size: px2vh(42);
				}

				.item-right {
					display: flex;
					flex-direction: column;
					align-items: flex-start;

					.item-name {
						font-size: 16px;
					}

					.item-dept {
						font-size: 14px;
					}
				}
			}
		}
	}
</style>
<style lang="scss">
	.select_content_tabs {

		/deep/.van-tabs__wrap {
			display: none !important;
		}
	}
</style>
